package org.hardcode.rpc.test.consumer.codec.handler;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.hardcode.rpc.protocol.RpcProtocol;
import org.hardcode.rpc.protocol.header.RpcHeaderFactory;
import org.hardcode.rpc.protocol.request.RpcRequest;
import org.hardcode.rpc.protocol.response.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RpcTestConsumerHandler extends SimpleChannelInboundHandler<RpcProtocol<RpcResponse>> {

    private final Logger logger = LoggerFactory.getLogger(RpcTestConsumerHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        logger.info("发送数据");
        //模拟发送数据
        RpcProtocol<RpcRequest> protocol = new RpcProtocol<>();
        protocol.setHeader(RpcHeaderFactory.getRequestHeader("jdk"));
        RpcRequest request = new RpcRequest();
        request.setClassName("org.hardcode.rpc.test.provider.service.DemoService");
        request.setGroup("hardCode");
        request.setMethodName("add");
        request.setParameters(new Object[]{1,3});
        request.setParameterTypes(new Class[]{Integer.class,Integer.class});
        request.setVersion("1.0.0");
        request.setAsync(false);
        request.setOneWay(false);
        protocol.setBody(request);
        logger.info("服务消费者发送数据====>:{}", JSONObject.toJSONString(protocol));
        ctx.writeAndFlush(protocol);
        logger.info("数据发送完毕");


    }

    //会在服务提供者和服务消费者之间成功建立 连接时触发
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcProtocol<RpcResponse> protocol) throws Exception {



        logger.info("服务消费者收到的数据===>:{}",JSONObject.toJSONString(protocol));

        Object result = protocol.getBody().getResult();
        logger.error("获取到的结果值:{}",result);
    }
}
